package br.com.quad.dao;

import java.util.List;

import br.com.quad.bean.Plano;
import br.com.quad.dao.HibernateDAOFactory;

public class PlanoDAOHibernate implements PlanoDAO {

	HibernateDAOFactory hibernateDAOFactory = null;
	HibernateDAO<Plano> hibernateDAO = null;

	public PlanoDAOHibernate() {
		hibernateDAOFactory = new HibernateDAOFactory();
		hibernateDAO = hibernateDAOFactory.getPlanoDAO();
	}

	@Override
	public boolean inserir(Plano plano) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.add(plano);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 
		return ok;
	}

	@Override
	public boolean alterar(Plano plano) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.update(plano);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}

		return ok;
	}

	@Override
	public boolean excluir(Plano plano) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.remove(plano);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 

		return ok;
	}

	@Override
	public Plano getPlano(int codigoPlano) {
		return hibernateDAO.get(codigoPlano);
	}

	@Override
	public List<Plano> getListarTodos() {
		return hibernateDAO.listAll();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Plano> getSelecionar(String descricao, int status) {
		String 	sql = "FROM Plano WHERE codigoPlano <> 0";

		if (!(descricao.isEmpty())) {
			sql += " AND descricao like '" + descricao + "%' ";  
		}

		if (status == 1) {
			sql += " AND status = "+status+"";  
		}

		sql += " ORDER BY descricao";		
 
		List<Plano> lista = hibernateDAO.getSession().createQuery(sql).list();

		return lista;
	}

	@Override
	public boolean isExclusaoLiberada(Plano plano) {
		// TODO Auto-generated method stub
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean isExiste(Plano plano) {
		String 	sql = 	" FROM Plano " +
						" WHERE descricao	= '"+ plano.getDescricao() + "' AND " +
						"		codigoPlano != '" + plano.getCodigoPlano() + "'";

		List<Plano> lista = hibernateDAO.getSession().createQuery(sql).list();

		if (lista.size()<1) {
			return false;
		} else {
			return true;
		}
	}
}
